﻿package com.singlenotion.net 
{
	import flash.display.InteractiveObject;
	import flash.events.EventDispatcher;
	import com.google.analytics.AnalyticsTracker; 
	import com.google.analytics.GATracker; 
	
	/**
	 * Tracking class to interface with the Google Analytics AS3 libraries. Ensure the Google Analytics library
	 * components are included in the file you want to track.
	 * 
	 * @author Adam Jowett (Single Notion)
	 * @version 1.0 (29-10-2009)
	 * @link http://www.singlenotion.com
	 * @see http://code.google.com/apis/analytics/docs/tracking/flashTrackingSetupFlash.html
	 * 
	 * @usage 
	 * 			GoogleTracker.init(this,"UA-7877676-98", true);
	 * 			GoogleTracker.trackPage("/home");
	 * 			GoogleTracker.trackEvent("Home", "Click", "Home button");
	 */
	public class GoogleTracker extends EventDispatcher
	{
		protected static var _tracker:AnalyticsTracker;
		protected static var _bridging:Boolean;

		public function GoogleTracker() 
		{
		}
		
		/**
		 * 
		 * @param	$scope - A reference to the scope to apply the tracker to, usually this would be "this"
		 * @param	$UA - A String that is your Google Analytics UA code
		 * @param	$debug - Boolean to show debugging messages on screen
		 */
		public static function init($scope:InteractiveObject, $UA:String, $debug:Boolean = true, $bridgingMode = false)
		{
			_tracker = new GATracker($scope, $UA, "AS3", $debug);
			_bridging = $bridgingMode;
		}
		
		/**
		 * trackPage is called when visiting pages
		 * @param	$page - A string representing the page visited.
		 */
		public static function trackPage($page:String):void
		{
			if ($page.indexOf("/") != 1) $page = "/" + $page;
			_tracker.trackPageview($page);
		}
		
		/**
		 * trackEvent is called when wanting to track user interaction.
		 * @param	$category - The name you supply for the group of objects you want to track.
		 * @param	$action - A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
		 * @param	$label - An optional string to provide additional dimensions to the event data.
		 * @param	$value - An integer that you can use to provide numerical data about the user event.
		 */
		public static function trackEvent($category:String, $action:String, $label:String = "", $value:Number = Infinity):void
		{
			if ($value != Infinity) {
				_tracker.trackEvent($category, $action, $label, $value);
			} else if ($label.length > 0 && $value == Infinity) {
				_tracker.trackEvent($category, $action, $label);
			} else {
				_tracker.trackEvent($category, $action);
			}
		}		
	}
}